package com.xdq.service.impl;

import com.xdq.bean.Address;
import com.xdq.bean.AddressNameCount;
import com.xdq.repository.AddressRepository;
import com.xdq.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author: 徐东强
 * @date: 2018/9/27 下午2:31
 * @description:
 **/
@Service
public class AddressServiceImpl implements AddressService {

    private final MongoTemplate mongoTemplate;

    private final AddressRepository addressRepository;

    @Autowired
    public AddressServiceImpl(MongoTemplate mongoTemplate, AddressRepository addressRepository) {
        this.mongoTemplate = mongoTemplate;
        this.addressRepository = addressRepository;
    }

    @Override
    public Optional<Address> save(Address address) {
        return Optional.ofNullable(this.addressRepository.save(address));
    }

    @Override
    public Optional<List<Address>> getAll(){
        return Optional.ofNullable(this.addressRepository.findAll());
    }

    @Override
    public Optional<Address> getOneById(String id) {
        return this.addressRepository.findById(id);
    }

    @Override
    public List<AddressNameCount> getCountByName() {
        TypedAggregation<Address> aggregation = Aggregation.newAggregation(Address.class,
                Aggregation.group("name").count().as("count"),
                Aggregation.project("count").and("name").previousOperation());
        return this.mongoTemplate.aggregate(aggregation, AddressNameCount.class)
                .getMappedResults();
    }
}
